package fr.mairie.parc.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

import org.apache.commons.io.IOUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

public class ExcelUtil {

	/**
	 * utility method for saving an Excel file 
	 * @param file
	 * @return
	 */
	public static void writeExcelFile(HSSFWorkbook workbook, File file) {
		OutputStream stream = null;
		try {
			stream = new BufferedOutputStream(new FileOutputStream(file));
		    workbook.write(stream);
		    stream.flush();
		} catch (IOException ex) {
		    throw new RuntimeException("Failed to write file", ex);
		} finally {
			IOUtils.closeQuietly(stream);
		}
	}

	/**
	 * utility method for loading an Excel file 
	 * @param file
	 * @return
	 */
	public static HSSFWorkbook loadExcelFile(File file) {
		HSSFWorkbook workbook;
		InputStream stream = null;
		try {
			stream = new BufferedInputStream(new FileInputStream(file));
			POIFSFileSystem fs = new POIFSFileSystem(stream);
			workbook = new HSSFWorkbook(fs);

		} catch (IOException ex) {
		    throw new RuntimeException("Failed to read file " + file, ex);
		} finally {
			IOUtils.closeQuietly(stream);
		}
		return workbook;
	}

	/**
	 * utility method for loading an Excel file 
	 * @param file
	 * @return
	 */
	public static HSSFWorkbook loadExcelFile(URL url) {
		HSSFWorkbook workbook;
		InputStream stream = null;
		try {
			stream = new BufferedInputStream(url.openStream());
			POIFSFileSystem fs = new POIFSFileSystem(stream);
			workbook = new HSSFWorkbook(fs);

		} catch (IOException ex) {
		    throw new RuntimeException("Failed to read url '" + url + "'", ex);
		} finally {
			IOUtils.closeQuietly(stream);
		}
		return workbook;
	}
	
	/**
	 * utility method for saving an Excel file content in memory
	 * @param file
	 * @return
	 */
	public static byte[] saveToByteArray(HSSFWorkbook w) {
		ByteArrayOutputStream stream = null;
		try {
			stream = new ByteArrayOutputStream();
		    w.write(stream);
		    stream.flush();
		} catch (IOException ex) {
		    throw new RuntimeException("Failed to write file", ex);
		} finally {
			IOUtils.closeQuietly(stream);
		}
		return stream.toByteArray();
	}

	
}
